﻿using System.Text;
using System.Web.UI.WebControls;

namespace easyVal.Web.Extensions
{
    public static class WebUIExtensions
    {
        public static void AddValidationAttributeEasy(this WebControl webControl, string ruleName, string ruleMessage)
        {
            AddValidationAttributeEasy(webControl, ruleName, ruleMessage, null);
        }

        public static void AddValidationAttributeEasy(this WebControl webControl, string ruleName, string ruleMessage,
                                                      string ruleParams)
        {
            // Clean parameters
            ruleParams = string.IsNullOrEmpty(ruleParams) ? "true" : ruleParams;
            ruleMessage = string.IsNullOrEmpty(ruleMessage) ? null : EscapeJavascriptString(ruleMessage);

            // Get validate attribute
            string validateAttr = webControl.Attributes["validate"];
            var builder = new StringBuilder(validateAttr);

            // Insert new validate attribute into webcontrol or append to existing
            if (builder.ToString() == "")
            {
                // Insert first ruleName
                builder.Append("{" + ruleName + ":" + ruleParams);

                // Insert first ruleMessage
                if (!string.IsNullOrEmpty(ruleMessage))
                    builder.Append(",messages:{" + ruleName + ":'" + ruleMessage + "'}");
                builder.Append("}");
            }
            else
            {
                // Insert ruleName
                int idxR = builder.ToString().IndexOf("{") + 1;
                builder.Insert(idxR, ruleName + ":" + ruleParams + ",");

                // Insert ruleMessage
                if (!string.IsNullOrEmpty(ruleMessage))
                {
                    int idxM = builder.ToString().IndexOf("messages:{") + 10;
                    builder.Insert(idxM, ruleName + ":'" + ruleMessage + "',");
                }
            }

            webControl.Attributes["validate"] = builder.ToString();
        }

        public static void ClearValidation(this WebControl control)
        {
            control.Attributes.Remove("validate");
        }

        private static string EscapeJavascriptString(string input)
        {
            return input == null ? null : input.Replace("\\", "\\\\").Replace("\'", "\\\'");
        }
    }
}